import { camelCase } from 'lodash'
import { useLocalStorage } from '@vueuse/core'
import { getUserInfo, userLogin } from '@/api/user.js'
import { dynamicRoutes } from '@/router/index.js'
import router from '../router'

export const useAuthStore = defineStore('auth', {
  state: () => {
    return {
      layoutRouteName: import.meta.env.VITE_LAYOUT_ROUTE_NAME,
      // 菜单树形结构
      treeMenus: [],
      // 当前用户的所有菜单
      menus: [],
      // 当前所有菜单，id为key,value为menu
      menusObj: {},
      // 登录状态 success, failed
      loginStatus: false,
      // 路由白名单，可以直接跳转
      whiteList: ['/register'],
      // 当前登录的token ，持久化到本地储存
      token: '',
      userInfo: {},
    }
  },
  actions: {
    getFirstRoute() {
      const arr = [...this.treeMenus]
      while (arr.length) {
        const menu = arr.shift()
        if (!menu) return
        if (menu.type === 'menu') return menu
        if (menu.children?.length) {
          arr.unshift(...menu.children)
        }
      }
    },
    initMenu() {
      this.menusObj = {}
      this.menus.forEach((i) => {
        i.children = []
        this.menusObj[i.id] = i
      })

      // 转为树形结构
      this.treeMenus = this.menus.filter((i) => {
        const parent = this.menusObj[i.parentId]
        if (parent) {
          parent.children.push(i)
          return false
        }
        return true
      })
      this.initDynamicRouter()
    },
    initDynamicRouter() {
      const viewsComponent = import.meta.glob('@/views/**/*.vue')
      router.addRoute({
        name: this.layoutRouteName,
        path: `/${this.layoutRouteName}`,
        component: () => import('@/layout/Basic/index.vue'),
      })
      this.menus.forEach((i) => {
        // 路由路径
        const path = this.getMenuLevelArr(i.id)
          .map((i) => i.path)
          .join('/')

        // 路由全路径
        const fullPath = `/${this.layoutRouteName}/${path}`
        i.fullPath = fullPath
        if (i.type === 'menu' && ['route', 'iframe'].includes(i.handleType)) {
          // 路由名称
          const name = this.getMenuLevelArr(i.id)
            .map((i) => i.name)
            .join('/')
          // 组件name
          const componentName = camelCase(fullPath)
          const dynamicRoute = {
            name,
            path,
            fullPath,
            // component: async () => {
            //   console.log(viewsComponent[i.component], 'viewsComponent[i.component]')

            //   const component = viewsComponent[i.component]
            //   console.log(componentName, 'componentName')

            //   if (!component) throw new Error(`${i.component} 文件不存在！`)
            //   return component().then((comp) => {
            //     return {
            //       ...comp.default,
            //       name: componentName,
            //     }
            //   })
            // },
            component: viewsComponent[i.component],
            meta: {
              title: i.title,
              cache: i.cache,
              component: i.component,
              icon: i.icon,
              componentName,
              id: i.id,
            },
          }
          i.componentName = componentName
          // console.log(dynamicRoute, 'dynamicRoute')

          router.addRoute(this.layoutRouteName, dynamicRoute)
          // console.log(router.getRoutes(), path, 'router')
        }
      })
    },
    getMenuLevelArr(id) {
      const arr = []
      let currentMenu = this.menusObj[id]
      while (currentMenu) {
        arr.unshift(currentMenu)
        currentMenu = this.menusObj[currentMenu.parentId]
      }
      return arr
    },
    async beforeEach(to) {
      // 白名单直接跳转
      if (this.whiteList.includes(to.fullPath)) {
        return
      }
      let path
      if (this.token && !this.loginStatus) {
        // 初始化登录逻辑
        this.loginStatus = 'success' // 登录成功
        this.menus = dynamicRoutes

        this.initMenu()
        return to.fullPath
      }
      // 如果是登录失败的，直接跳转到登录页
      if (this.loginStatus !== 'success') {
        path = '/login'
      } else {
        // 如果是登录成功的，并且路由是根路径或者登录页的，跳转到菜单第一个路由
        if (['/', '/login'].includes(to.fullPath)) {
          path = this.getFirstRoute()?.fullPath
          console.log(path, 'pathpathpath')
        } else {
          return path
        }
      }
      // 重定向路由和原跳转路由路径相同，则无需处理
      if (to.fullPath !== path) {
        return path
      }
    },
    setToken(val) {
      this.token = val
    },
    async setLoginUserInfo(loginUserInfo) {
      this.loginStatus = 'success' // 登录成功
      this.setToken(loginUserInfo.token.accessToken)
      await getUserInfo({ username: loginUserInfo.username }).then(async (res) => {
        this.userInfo = res.data
        this.menus = loginUserInfo.menus

        this.initMenu()
      })
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: sessionStorage,
        paths: ['userInfo', 'token'],
      },
    ],
  },
})
